package zencstudio.sgrealtor.view.common;

import java.io.IOException;

import zencstudio.sgrealtor.R;
import zencstudio.sgrealtor.model.GCMRegisterRequest;
import zencstudio.sgrealtor.model.POSTResponse;
import zencstudio.sgrealtor.service.IWireFrameService;
import zencstudio.sgrealtor.service.WireFrameServiceFactory;
import zencstudio.sgrealtor.utils.Const;
import zencstudio.sgrealtor.utils.DeviceInfo;
import zencstudio.sgrealtor.utils.WFUtils;
import zencstudio.sgrealtor.view.phone.MainActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class SplashActivity extends Activity{
	private GoogleCloudMessaging gcm;
	private String regid;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splashscreen);
		DeviceInfo.setup(this);
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				 // Check device for Play Services APK. If check succeeds, proceed with GCM registration.
		        if (WFUtils.checkPlayServices(SplashActivity.this)) {
		            gcm = GoogleCloudMessaging.getInstance(SplashActivity.this);
		            regid = WFUtils.getRegistrationId(SplashActivity.this);

		            if (regid.isEmpty()) {
		                registerInBackground();
		            }
		        } else {
		            Log.i("SplashActivity", "No valid Google Play Services APK found.");
		        }
		        handler.sendMessageDelayed(handler.obtainMessage(), 2000);
			}
		});
		thread.start();
		
	}
	 /**
     * Registers the application with GCM servers asynchronously.
     * <p>
     * Stores the registration ID and the app versionCode in the application's
     * shared preferences.
     */
    private String registerInBackground() {     
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(this);
                    }
                    regid = gcm.register(Const.SENDER_ID);
                    msg = "Device registered, registration ID=" + regid;

                    // You should send the registration ID to your server over HTTP, so it
                    // can use GCM/HTTP or CCS to send messages to your app.
                    if(sendRegistrationIdToBackend(regid))
                    	storeRegistrationId(this, regid);
                    // For this demo: we don't need to send it because the device will send
                    // upstream messages to a server that echo back the message using the
                    // 'from' address in the message.

                    // Persist the regID - no need to register again.
                    
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                    // If there is an error, don't just keep trying to register.
                    // Require the user to click a button again, or perform
                    // exponential back-off.
                }
                return msg;                    
    }
    /**
     * Stores the registration ID and the app versionCode in the application's
     * {@code SharedPreferences}.
     *
     * @param context application's context.
     * @param regId registration ID
     */
    private void storeRegistrationId(Context context, String regId) {
    	WFUtils.saveValue(this,Const.PROPERTY_REG_ID, regId);
    	int appVersion = WFUtils.getAppVersion(context);
    	WFUtils.saveIntValue(this,Const.PROPERTY_APP_VERSION, appVersion);
    }
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			startActivity(new Intent(SplashActivity.this, MainActivity.class));
			//startActivity(new Intent(SplashActivity.this, ContactActivity.class));
			SplashActivity.this.finish();
		}
	};
	/**
     * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
     * messages to your app. Not needed for this demo since the device sends upstream messages
     * to a server that echoes back the message using the 'from' address in the message.
     */
    private boolean sendRegistrationIdToBackend(String id) {
    	GCMRegisterRequest request = new GCMRegisterRequest();
    	request.key = id;
    	IWireFrameService service = WireFrameServiceFactory.getInstance().getService();
    	POSTResponse response = null;
    	try {
			response = service.registerGCMKey(request);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
    	if(!response.isResult() && getString(R.string.gcm_key_exist).equalsIgnoreCase(response.getMsg()))
    		return true;
    	else if(!response.isResult())
    		Toast.makeText(this, R.string.gcm_error_register, Toast.LENGTH_LONG).show();
    	return response.isResult();
    }
}
